#include "JsonObjectBase.hxx"

using namespace std;
using namespace neb;

static const ASString strCommands[] = {
    "",
#undef defineTypeStr
#define defineTypeStr(_enum, _name, _type) _name,
        ASJsonCommandMap(defineTypeStr)
#undef defineTypeStr
#define defineTypeStr(_enum, _name, _type) _name"Response",
        ASJsonCommandMap(defineTypeStr)
#undef defineTypeStr
};

static const ASString strFieldSequence("Sequence");
static const ASString strFieldCommand("Command");

JsonObject::JsonObject(Type t) : mType(t)
{
}

JsonObject::JsonObject(const ASString & strJson) : CJsonObject(strJson)
{
    mType = Unknown;
    ASString command;
    if (!IsEmpty() && Get(strFieldCommand, command))
    {
        for (int i = 1; i < MAXType; ++i)
        {
            if (command == strCommands[i])
            {
                mType = static_cast<Type>(i);
                break;
            }
        }
    }
}


//////////////////////////////////////////////////////////////////////////
JsonObjectBase::JsonObjectBase(JsonObject::Type t, const ASString& seq)
    : mBaseObj(new JsonObject(t))
    , mSequence(seq)
    , mBuild(false)
{
    if (t > JsonObject::Unknown && t < JsonObject::MAXType)
    {
        mCommand = strCommands[t];
    }
}

JsonObjectBase::JsonObjectBase(JsonObject* base)
    : mBaseObj(base)
    , mBuild(true)
{
    if (!mBaseObj->IsEmpty())
    {
        mBaseObj->Get(strFieldSequence, mSequence);
        mBaseObj->Get(strFieldCommand, mCommand);
    }
}

JsonObjectBase::~JsonObjectBase()
{
    if (mBaseObj)
    {
        delete mBaseObj;
    }
}

ASString JsonObjectBase::toString(bool formatted /*= false*/)
{
    if (!mBuild)
    {
        mBaseObj->Add(strFieldSequence, mSequence);
        mBaseObj->Add(strFieldCommand, mCommand);

        mBuild = true;
    }

    return  const_cast<JsonObjectBase*>(this)->to_string(formatted);
}

